﻿using JT808Protocol.Models;
using System;
using System.Collections.Concurrent;

namespace JT808Gateway.Core
{
    public class CacheService
    {
        private ConcurrentDictionary<string, object> Cache;

        public CacheService()
        {
            Cache = new ConcurrentDictionary<string, object>();
        }

        public void StoreCache(JT808Package package)
        {
            var sim = package.Header.SimNumber;
            Cache[CacheKeyDefaults.SerialNum + sim] = package.Header.SerialNumber;
            Cache[CacheKeyDefaults.Version + sim] = package.Header.ProtocolVersion;
            Cache[CacheKeyDefaults.ReportTime + sim] = DateTime.Now;
        }

        public void StoreSerialNum(JT808Package package)
        {
            var sim = package.Header.SimNumber;
            Cache[CacheKeyDefaults.SerialNum + sim] = package.Header.SerialNumber;
        }

        public ushort? GetSerialNum(string simNumber)
        {
            if (Cache.TryGetValue(CacheKeyDefaults.SerialNum + simNumber, out var obj))
            {
                return (ushort)obj;
            }
            return null;
        }

        public DateTime? GetReportTime(string simNumber)
        {
            if (Cache.TryGetValue(CacheKeyDefaults.ReportTime + simNumber, out var obj))
            {
                return (DateTime)obj;
            }
            return null;
        }

        public JT808ProtocolVersion? GetVersion(string simNumber)
        {
            if (Cache.TryGetValue(CacheKeyDefaults.Version + simNumber, out var obj))
            {
                return (JT808ProtocolVersion)obj;
            }
            return null;
        }
    }
}